import { isArray, isObject } from "../Utils/types.ts";
import { getRandomForRange } from "../Utils/Maths.ts";
import { sha256 } from "../../Native/Module/Crypto.ts";
import { HttpMethod, JavaNetModel, JavaNetParams } from "./NetParams.ts";

const BASE_URL = "https://yupao-test.yupaowang.com/";


function sortObj(params: any) {
  if (params == null) return params;
  if (isArray(params)) {
    return params.reduce((acc: any, item: any) => {
      if (isObject(item)) {
        acc.push(sortObj(item));
      } else {
        acc.push(item);
      }
      return acc;
    }, []);
  } else if (isObject(params)) {
    return Object.keys(params)
      .sort()
      .reduce((acc: any, key) => {
        const value = params[key];
        if (isObject(value)) {
          acc[key] = sortObj(value);
        } else {
          acc[key] = value;
        }
        return acc;
      }, {});
  } else {
    return params;
  }
}

function createSignStr(timestamp: number, nonce: number, params?: {}) {
  const sortParams = sortObj({ ...params, timestamp, nonce });
  if (isArray(sortParams)) {
    throw "不支持的数据类型";
  } else if (isObject(sortParams)) {
    let result = "";
    Object.keys(sortParams)
      .forEach(key => {
        const value = sortParams[key];
        if (isArray(value) || isObject(value)) {
          result += `${key}=${JSON.stringify(value)}&`;
        } else {
          result += `${key}=${value}&`;
        }
      });
    result += "8k&^$Hsk1?kkcj12^99K1ia";
    console.log(`sign str=${result}`);
    return result;
  } else {
    throw "不支持的数据类型";
  }
}

function createSign(timestamp: number, nonce: number, params?: {}): string {
  const signStr = createSignStr(timestamp, nonce, params);
  return sha256(signStr) || signStr;
}

function genHeader(customHeader?: {}, params?: {}): {} {
  const timestamp = Date.now();
  const nonce = getRandomForRange(1, 999998);
  return {
    runtimeVersion: 13,
    channel: "dev",
    advertisingId: "5519b691e4d153f33f7f4af2d9ab4e449137af58386e93550ba8709002c4936e",
    source: "android",
    deviceId: "36d924c55567b9dd",
    deviceName: "V2219A",
    uid: "20057142",
    osVersion: 13,
    model: "V2219A",
    packageName: "io.dcloud.H576E6CC7",
    brand: "vivo",
    os: "ANDROID",
    business: "YPZP",
    packageVersionCode: "300601111",
    runtime: "ANDROID",
    packageVersion: "6.0.1",
    userrole: 2,
    token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDU3MTY3MjMsImV4cCI6MTcxNjA4NDcyMywiZGF0YSI6eyJzaW5nbGUiOiJXSk0zMkg1U0dQSFA0TURBIiwidWlkIjoyMDA1NzE0MiwiYnVzaW5lc3MiOiIxIiwic3lzdGVtX3R5cGUiOiJhbmRyb2lkIiwibWluaV90b2tlbiI6IldKTTMySDVTR1BIUDRNREEiLCJpZCI6MjAwNTcxNDIsInV1aWQiOjIwMDU3MTQyfSwidG9rZW4iOnsicmVnUnQiOiJhbmRyb2lkIiwidGVuYW50S2V5IjoiWVBaUCIsInRlbmFudElkIjoyMDA1NzE0MiwicGFja2FnZU5hbWUiOiJpby5kY2xvdWQuSDU3NkU2Q0M3IiwidXNlcklkIjoyMDA1NzE0MiwidG9rZW4iOiJXSk0zMkg1U0dQSFA0TURBIn19.6hwDZq0zumVbOFsiwf3-uaNwgArLV9I6Vq8D--sFpzU",
    reqsource: "YPZP",
    imei: "36d924c55567b9dd",
    sdkVersion: "1.0.1",
    "user-agent": "YP YPZP vivo V2219A 13 6.0.1 36d924c55567b9dd 1704957255710",
    nonce: nonce,
    timestamp: timestamp,
    sign: createSign(timestamp, nonce, params),
    signVersion: 1,
    "Content-Type": "application/json; charset=UTF-8",
    ...customHeader
  };
}


async function javaFetch<T>(params: JavaNetParams) {
  const url = `${BASE_URL}${params.url}`;
  const method = (params.method || HttpMethod.POST).valueOf();
  return fetch(url, {
    body: JSON.stringify(params.params),
    method: method,
    headers: genHeader(params.headers, params.params)
  }).then(async function(response) {
    let json = await response.json();
    console.log(`java url=${url} result=${JSON.stringify(json)}`);
    return json as JavaNetModel<T>;
  });
}

export default javaFetch;
